import { ref, computed, unref } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { checkOnlyUser } from '/@/api/sys/user';
export var LoginStateEnum;
(function (LoginStateEnum) {
    LoginStateEnum[LoginStateEnum["LOGIN"] = 0] = "LOGIN";
    LoginStateEnum[LoginStateEnum["REGISTER"] = 1] = "REGISTER";
    LoginStateEnum[LoginStateEnum["RESET_PASSWORD"] = 2] = "RESET_PASSWORD";
    LoginStateEnum[LoginStateEnum["MOBILE"] = 3] = "MOBILE";
    LoginStateEnum[LoginStateEnum["QR_CODE"] = 4] = "QR_CODE";
})(LoginStateEnum || (LoginStateEnum = {}));
export var SmsEnum;
(function (SmsEnum) {
    SmsEnum["LOGIN"] = "0";
    SmsEnum["REGISTER"] = "1";
    SmsEnum["FORGET_PASSWORD"] = "2";
})(SmsEnum || (SmsEnum = {}));
const currentState = ref(LoginStateEnum.LOGIN);
export function useLoginState() {
    function setLoginState(state) {
        currentState.value = state;
    }
    const getLoginState = computed(() => currentState.value);
    function handleBackLogin() {
        setLoginState(LoginStateEnum.LOGIN);
    }
    return { setLoginState, getLoginState, handleBackLogin };
}
export function useFormValid(formRef) {
    async function validForm() {
        const form = unref(formRef);
        if (!form)
            return;
        const data = await form.validate();
        return data;
    }
    return { validForm };
}
export function useFormRules(formData) {
    const { t } = useI18n();
    const getAccountFormRule = computed(() => createRule(t('sys.login.accountPlaceholder')));
    const getPasswordFormRule = computed(() => createRule(t('sys.login.passwordPlaceholder')));
    const getSmsFormRule = computed(() => createRule(t('sys.login.smsPlaceholder')));
    const getMobileFormRule = computed(() => createRule(t('sys.login.mobilePlaceholder')));
    const getRegisterAccountRule = computed(() => createRegisterAccountRule('account'));
    const getRegisterMobileRule = computed(() => createRegisterAccountRule('mobile'));
    const validatePolicy = async (_, value) => {
        return !value ? Promise.reject(t('sys.login.policyPlaceholder')) : Promise.resolve();
    };
    const validateConfirmPassword = (password) => {
        return async (_, value) => {
            if (!value) {
                return Promise.reject(t('sys.login.passwordPlaceholder'));
            }
            if (value !== password) {
                return Promise.reject(t('sys.login.diffPwd'));
            }
            return Promise.resolve();
        };
    };
    const getFormRules = computed(() => {
        const accountFormRule = unref(getAccountFormRule);
        const passwordFormRule = unref(getPasswordFormRule);
        const smsFormRule = unref(getSmsFormRule);
        const mobileFormRule = unref(getMobileFormRule);
        const registerAccountRule = unref(getRegisterAccountRule);
        const registerMobileRule = unref(getRegisterMobileRule);
        const mobileRule = {
            sms: smsFormRule,
            mobile: mobileFormRule,
        };
        switch (unref(currentState)) {
            // register form rules
            case LoginStateEnum.REGISTER:
                return {
                    account: registerAccountRule,
                    password: passwordFormRule,
                    mobile: registerMobileRule,
                    sms: smsFormRule,
                    confirmPassword: [{ validator: validateConfirmPassword(formData?.password), trigger: 'change' }],
                    policy: [{ validator: validatePolicy, trigger: 'change' }],
                };
            // reset password form rules
            case LoginStateEnum.RESET_PASSWORD:
                return {
                    username: accountFormRule,
                    confirmPassword: [{ validator: validateConfirmPassword(formData?.password), trigger: 'change' }],
                    ...mobileRule,
                };
            // mobile form rules
            case LoginStateEnum.MOBILE:
                return mobileRule;
            // login form rules
            default:
                return {
                    account: accountFormRule,
                    password: passwordFormRule,
                };
        }
    });
    return { getFormRules };
}
function createRule(message) {
    return [
        {
            required: true,
            message,
            trigger: 'change',
        },
    ];
}
function createRegisterAccountRule(type) {
    return [
        {
            validator: type == 'account' ? checkUsername : checkPhone,
            trigger: 'change',
        },
    ];
}
function checkUsername(rule, value, callback) {
    const { t } = useI18n();
    if (!value) {
        return Promise.reject(t('sys.login.accountPlaceholder'));
    }
    else {
        return new Promise((resolve, reject) => {
            checkOnlyUser({ username: value }).then((res) => {
                res.success ? resolve() : reject('用户名已存在!');
            });
        });
    }
}
async function checkPhone(rule, value, callback) {
    const { t } = useI18n();
    var reg = /^1[3456789]\d{9}$/;
    if (!reg.test(value)) {
        return Promise.reject(new Error('请输入正确手机号'));
    }
    else {
        return new Promise((resolve, reject) => {
            checkOnlyUser({ phone: value }).then((res) => {
                res.success ? resolve() : reject('手机号已存在!');
            });
        });
    }
}
//update-begin---author:wangshuai ---date:20220629  for：[issues/I5BG1I]vue3不支持auth2登录------------
/**
 * 判断是否是OAuth2APP环境
 */
export function isOAuth2AppEnv() {
    return /wxwork|dingtalk/i.test(navigator.userAgent);
}
/**
 * 后台构造oauth2登录地址
 * @param source
 */
export function sysOAuth2Login(source) {
    let url = `${window._CONFIG['domianURL']}/sys/thirdLogin/oauth2/${source}/login`;
    url += `?state=${encodeURIComponent(window.location.origin)}`;
    window.location.href = url;
}
//update-end---author:wangshuai ---date:20220629  for：[issues/I5BG1I]vue3不支持auth2登录------------
